package com.ruicar.afs.cloud.afscase.infomanagement.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruicar.afs.cloud.afscase.channel.utils.CaseConfig;
import com.ruicar.afs.cloud.afscase.common.dto.ProductInfoDTO;
import com.ruicar.afs.cloud.afscase.common.feign.FinanceProductFeign;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.CaseBaseInfo;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.CaseCarInfo;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.CaseChannelInfo;
import com.ruicar.afs.cloud.afscase.infomanagement.service.*;
import com.ruicar.afs.cloud.bizcommon.algorithm.service.FinanceCalculatorService;
import com.ruicar.afs.cloud.bizcommon.business.dto.CalculatorDTO;
import com.ruicar.afs.cloud.bizcommon.business.dto.CalculatorListDTO;
import com.ruicar.afs.cloud.bizcommon.business.entity.FinCostDetails;
import com.ruicar.afs.cloud.bizcommon.business.entity.FinDiscountDetails;
import com.ruicar.afs.cloud.bizcommon.business.mapper.ApplyCostDetailsMapper;
import com.ruicar.afs.cloud.bizcommon.business.service.ApplyCostDetailsService;
import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.parameter.commom.enums.CostType;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: 金融产品
 * @author: sijun.yu
 * @date: 2020/8/4 19:50
 */
@Slf4j
@Service
@AllArgsConstructor
public class CaseProductServiceImpl extends ServiceImpl<ApplyCostDetailsMapper, FinCostDetails> implements CaseProductService {

    private CaseConfig config;
    private FinanceProductFeign productFeign;
    private FinanceCalculatorService financeCalculatorService;
    private ApplyCostDetailsService costDetailsService;
    private CaseBaseInfoService caseBaseInfoService;
    private CaseCarInfoService caseCarInfoService;
    private CaseChannelInfoService caseChannelInfoService;
    private CaseDiscountDetailService  discountDetailService;

    /**
     * 获取产品请求头
     *
     * @return
     */
    public Map makeProductHeader() {
        Map<String, String> headers = new HashMap<>();
        headers.put("clientId", config.getProductClientId());
        headers.put("clientSecret", config.getProductClientSecret());
        return headers;
    }

    /**
     * 查询产品详情
     * @param condition
     * @return
     */
    public IResponse queryProductDetails(CalculatorDTO condition) {

        ProductInfoDTO dto = new ProductInfoDTO();
        dto.setId(condition.getId());
        IResponse iResponse = productFeign.queryProductDetails(dto, this.makeProductHeader());
        return iResponse;
    }

    /**
     * 获取产品利率
     * @param condition
     * @return
     */
    public IResponse getProductRate(CalculatorDTO condition) {

        ProductInfoDTO dto = new ProductInfoDTO();
        CaseBaseInfo caseBaseInfo = caseBaseInfoService.getOne(Wrappers.<CaseBaseInfo>query().lambda().eq(CaseBaseInfo::getApplyNo,condition.getApplyNo()));
        dto.setId(condition.getId());
        if(caseBaseInfo!=null){
            dto.setAtomInfo(caseBaseInfo);
        }
        CaseCarInfo caseCarInfo = caseCarInfoService.getOne(Wrappers.<CaseCarInfo>query().lambda().eq(CaseCarInfo::getApplyNo,condition.getApplyNo()));
        if(caseBaseInfo!=null){
            dto.setCarInfo(caseCarInfo);
        }
        CaseChannelInfo caseChannelInfo = caseChannelInfoService.getOne(Wrappers.<CaseChannelInfo>query().lambda().eq(CaseChannelInfo::getApplyNo,condition.getApplyNo()));
        if(caseChannelInfo!=null){
            dto.setChannelInfo(caseChannelInfo);
        }
        // 利率信息
        if (CostType.CARAMT.getIndex().equals(condition.getCostType())) {
            FinCostDetails mainProductInfo = new FinCostDetails();
            mainProductInfo.setProductId(condition.getId().toString());
            mainProductInfo.setLoanTerm(condition.getLoanTerm());
            dto.setMainProductInfo(mainProductInfo);
        } else if (CostType.AFFIXAMT.getIndex().equals(condition.getCostType())) {
            FinCostDetails addProductInfo = new FinCostDetails();
            addProductInfo.setLoanTerm(condition.getLoanTerm());
            addProductInfo.setProductId(condition.getAddId().toString());
            dto.setAddProductInfo(addProductInfo);
        }
        IResponse<JSONObject> iResponse = productFeign.getCustomerRate(dto, this.makeProductHeader());
        if(CommonConstants.SUCCESS.equals(iResponse.getCode())){
            return iResponse;
        }
        // 车辆
        if (CostType.CARAMT.getIndex().equals(condition.getCostType())) {
            if(iResponse.getData().getJSONObject("main")==null){
                return IResponse.fail("客户利率为空，请输入正确产品期数");
            }
        }else{
            if(iResponse.getData().getJSONObject("son")==null){
                return IResponse.fail("客户利率为空，请输入正确产品期数");
            }
        }
        return iResponse;
    }

    /**
     * 调用计算器，生成2个还款计划表
     * @param list
     * @return
     */
    public IResponse financeCalculation(List<CalculatorDTO> list) {

        IResponse iResponse = financeCalculatorService.getMultipleRepaymentPlan(list);
        return iResponse;
    }

    /**
     * 更新融资列表信息
     *
     * @param applyNo
     * @param inList
     */
    public List<FinCostDetails> updateCostList(String applyNo, List<CalculatorDTO> inList) {

        CaseCarInfo caseCarInfo = caseCarInfoService.getOne(Wrappers.<CaseCarInfo>query().lambda().eq(CaseCarInfo::getApplyNo,applyNo));

        CaseChannelInfo  caseChannelInfo= caseChannelInfoService.getOne(Wrappers.<CaseChannelInfo>query().lambda()
        .eq(CaseChannelInfo::getApplyNo,applyNo));

        for (CalculatorDTO condition : inList) {
            FinDiscountDetails  finDiscountDetails=discountDetailService.getOne(Wrappers.<FinDiscountDetails>query().lambda()
                    .eq(FinDiscountDetails::getApplyNo,applyNo)
                    .eq(FinDiscountDetails::getDiscountId,"0")
            .eq(FinDiscountDetails::getCostType,condition.getCostType()));
            // 贴息明细
            List<FinDiscountDetails> discountList = condition.getDiscountList();
            if(discountList!=null && discountList.size()>0){
                for(FinDiscountDetails discountDetails:discountList){
                    if("0".equals(discountDetails.getDiscountId())){// 0-厂商
                        discountDetails.setDiscountParty(finDiscountDetails.getDiscountParty());
                    }else if("1".equals(discountDetails.getDiscountId())){// 1-合作商
                        discountDetails.setDiscountParty(caseChannelInfo.getDealerName());
                    }else if("2".equals(discountDetails.getDiscountId())){// 2-车商
                        discountDetails.setDiscountParty(caseChannelInfo.getCarDealersName());
                    }
                }
            }
        }

        List<FinCostDetails> resultList = costDetailsService.updateCostDetailsList(applyNo, caseCarInfo.getId(), inList);
        return resultList;
    }

    /**
     * 金融产品-调用计算器
     * @param condition
     * @return
     */
    public IResponse financeProductCalculation(CalculatorListDTO condition){

        String productId = condition.getProductId();
        Assert.isTrue(productId != null,"金融产品不能为空");

        // 获取产品详情
        ProductInfoDTO dto = new ProductInfoDTO();
        dto.setId(Long.valueOf(productId));
        IResponse<JSONObject> productJson = productFeign.queryProductDetails(dto, this.makeProductHeader());

        // 获取算法参数
        CalculatorDTO carProuctDto = null;// 车款
        CalculatorDTO addProductDto = null;// 附加贷
        List<CalculatorDTO> costList = condition.getCostList();
        for(CalculatorDTO calculatorDto:costList){
            String costType = calculatorDto.getCostType();
            if(CostType.CARAMT.getIndex().equals(costType)){
                carProuctDto = calculatorDto;
            }else if(CostType.AFFIXAMT.getIndex().equals(costType)){
                addProductDto = calculatorDto;
            }
        }
        Assert.isTrue(carProuctDto != null,"车款融资信息不能为空");
        // 调用计算器
        List<CalculatorDTO> inList = financeCalculatorService.getProductParameter(productJson.getData(),carProuctDto,addProductDto);
        return this.financeCalculation(inList);
    }

}
